import React, { createContext, ReactNode, useContext, useState } from 'react';

export type MeasurementValue = number | string | { [key: string]: number | string };

export type MeasurementData = {
    value: MeasurementValue;
    unit: string | { [key: string]: string };
    rawData: string;
    timestamp: string;
    isTested?: boolean; // 添加标识，用于区分是否已测试（主要用于酒精测试）
};

export type TestResult = {
    deviceRoute: string;
    deviceName: string;
    measurement: MeasurementData;
    status: 'normal' | 'warning' | 'danger';
    completedAt: Date;
    level?: number; // 添加可选的level属性，用于健康等级评估
};

interface TestResultsContextType {
    testResults: { [key: string]: TestResult };
    addTestResult: (deviceRoute: string, deviceName: string, measurement: MeasurementData) => void;
    removeTestResult: (deviceRoute: string) => void;
    getTestResult: (deviceRoute: string) => TestResult | undefined;
    clearAllResults: () => void;
}

const TestResultsContext = createContext<TestResultsContextType | undefined>(undefined);

export const useTestResults = () => {
    const context = useContext(TestResultsContext);
    if (!context) {
        throw new Error('useTestResults must be used within a TestResultsProvider');
    }
    return context;
};

interface TestResultsProviderProps {
    children: ReactNode;
}

export const TestResultsProvider: React.FC<TestResultsProviderProps> = ({ children }) => {
    const [testResults, setTestResults] = useState<{ [key: string]: TestResult }>({});

    // 根据测试值判断状态的辅助函数
    const getTestStatus = (deviceRoute: string, value: MeasurementValue, isTested?: boolean): 'normal' | 'warning' | 'danger' => {
        // 这里可以根据不同设备的正常值范围来判断状态
        switch (deviceRoute) {
            case 'SpO2':
                if (typeof value === 'object' && 'SpO2' in value) {
                    const spo2Value = Number(value.SpO2);
                    if (spo2Value >= 95) return 'normal';
                    if (spo2Value >= 90) return 'warning';
                    return 'danger';
                }
                break;
            case 'VitalCapacity':
                const vcValue = Number(value);
                if (vcValue >= 3000) return 'normal';
                if (vcValue >= 2000) return 'warning';
                return 'danger';
            case 'Alcohol':
                // 如果isTested为false，表示未测试，返回normal状态但会在UI中特殊处理
                if (isTested === false) return 'normal';
                
                const alcoholValue = Number(value);
                if (alcoholValue === 0) return 'normal';
                if (alcoholValue < 0.2) return 'warning';
                return 'danger';
            case 'Dynamometer':
                if (typeof value === 'object' && 'grip' in value) {
                    const gripValue = Number(value.grip);
                    if (gripValue >= 30) return 'normal';
                    if (gripValue >= 20) return 'warning';
                    return 'danger';
                }
                break;
            case 'Reaction':
                const reactionValue = Number(value);
                if (reactionValue < 300) return 'normal';
                if (reactionValue < 500) return 'warning';
                return 'danger';
            case 'Flicker':
                const flickerValue = Number(value);
                if (flickerValue > 40) return 'normal';
                if (flickerValue > 25) return 'warning';
                return 'danger';
        }
        return 'normal';
    };

    const addTestResult = (deviceRoute: string, deviceName: string, measurement: MeasurementData) => {
        const status = getTestStatus(deviceRoute, measurement.value, measurement.isTested);
        const testResult: TestResult = {
            deviceRoute,
            deviceName,
            measurement,
            status,
            completedAt: new Date()
        };

        setTestResults(prev => ({
            ...prev,
            [deviceRoute]: testResult
        }));
    };

    const removeTestResult = (deviceRoute: string) => {
        setTestResults(prev => {
            const newResults = { ...prev };
            delete newResults[deviceRoute];
            return newResults;
        });
    };

    const getTestResult = (deviceRoute: string): TestResult | undefined => {
        return testResults[deviceRoute];
    };

    const clearAllResults = () => {
        setTestResults({});
    };

    return (
        <TestResultsContext.Provider value={{
            testResults,
            addTestResult,
            removeTestResult,
            getTestResult,
            clearAllResults
        }}>
            {children}
        </TestResultsContext.Provider>
    );
};